// pages/user/profile/index.ts
import { getToken, removeToken } from '../../../utils/api';

Page({
  data: {
    isLoggedIn: false,
    userInfo: null as any,
    loading: false,
  },

  onLoad() {
    this.checkLoginStatus();
  },

  onShow() {
    this.checkLoginStatus();
  },

  checkLoginStatus() {
    const token = getToken();
    const isLoggedIn = !!token;
    this.setData({ isLoggedIn });
    
    if (isLoggedIn) {
      this.loadUserInfo();
    }
  },

  async loadUserInfo() {
    this.setData({ loading: true });
    // 这里可以加载用户信息
    // 暂时模拟用户信息
    this.setData({
      userInfo: {
        username: '微信用户',
        avatar: '/images/default-avatar.png'
      },
      loading: false
    });
  },

  onLogin() {
    wx.navigateTo({
      url: '/pages/login/index',
    });
  },

  onMyRecords() {
    if (!this.data.isLoggedIn) {
      this.onLogin();
      return;
    }
    wx.navigateTo({
      url: '/pages/travel/my-records/index',
    });
  },

  onCreateRecord() {
    if (!this.data.isLoggedIn) {
      this.onLogin();
      return;
    }
    wx.navigateTo({
      url: '/pages/travel/create/index',
    });
  },

  onLogout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          removeToken();
          this.setData({
            isLoggedIn: false,
            userInfo: null,
          });
          wx.showToast({
            title: '已退出登录',
            icon: 'success',
          });
        }
      },
    });
  },

  onSettings() {
    wx.navigateTo({
      url: '/pages/user/settings/index',
    });
  },
});
